import {getInfo, login, logout} from "@/api/login";
import {getToken, removeToken, setToken} from "@/utils/auth";

const user = {
    state: {
        token: getToken(),
        roles: [],
        permissions: [],
        name: '',
        avatar: '',
    },
    mutations: {
        SET_TOKEN: (state, token) => {
            state.token = token;
        },
        SET_ROLES: (state, roles) => {
            state.roles = roles;
        },
        SET_PERMISSIONS: (state, permissions) => {
            state.permissions = permissions;
        },
        SET_NAME: (state, name) => {
            state.name = name;
        },
        SET_AVATAR: (state, avatar) => {
            state.avatar = avatar;
        }
    },
    actions: {
        Login({commit}, userInfo) {
            this.loading = true;
            const username = userInfo.username.trim();
            const password = userInfo.password.trim();
            const code = userInfo.code;
            const uuid = userInfo.uuid;
            return new Promise((resolve, reject) => {
                login(username, password, code, uuid).then((response) => {
                    setToken(response.data.token);
                    commit('SET_TOKEN', response.data.token);
                    resolve(response);
                }).catch(error => {
                    reject(error);
                })
            })

        },
        GetInfo({commit}) {
            return new Promise((resolve, reject) => {
                getInfo().then(response => {
                    const user = response.data.user;
                    const avatar = (user.avatar === "" || user.avatar === null) ?
                        require("@/assets/images/profile.jpg") : process.env.VUE_APP_BASE_URL + user.avatar;
                    if (response.data.roles && response.data.roles.length > 0) {
                        commit('SET_ROLES', response.data.roles);
                        commit('SET_PERMISSIONS', response.data.permissions);
                    } else {
                        commit('SET_ROLES', ['ROLE_DEFAULT']);
                    }
                    commit('SET_NAME', user.username);
                    commit('SET_AVATAR', avatar);
                    resolve(response)
                }).catch(error => {
                    reject(error)
                })
            })
        },
        Logout({commit, state}) {
            return new Promise((resolve, reject) => {
                logout().then(() => {
                    commit('SET_TOKEN', '')
                    commit('SET_ROLES', [])
                    commit('SET_PERMISSIONS', [])
                    removeToken();
                    resolve();
                }).catch(err => {
                    reject(err);
                })
            })
        }
    },
}


export default user;
